package com.eastfair.venueservice.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eastfair.boot.request.PageParams;
import com.eastfair.boot.service.SuperServiceImpl;
import com.eastfair.core.exception.BizException;
import com.eastfair.venueservice.dao.LogisticsOrderMapper;
import com.eastfair.venueservice.dto.LoadOrderDTO;
import com.eastfair.venueservice.dto.LogisticsOrderPageQuery;
import com.eastfair.venueservice.entity.CreatCode;
import com.eastfair.venueservice.entity.LogisticsOrder;
import com.eastfair.venueservice.enums.LogisticsOrderTypeEnum;
import com.eastfair.venueservice.service.LogisticsOrderService;
import com.eastfair.venueservice.vo.LoadDetailsVo;
import com.eastfair.venueservice.vo.LogisticsOrderVo;
import io.seata.common.util.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 智慧物流 物流订单
 *
 * @author Du Xiaobo
 * @date 2023/5/9 11:03
 */
@Service
@Slf4j
public class LogisticsOrderServiceImpl extends SuperServiceImpl<LogisticsOrderMapper, LogisticsOrder> implements LogisticsOrderService {

    private static final String REFUND_NUM_FIELD = "order_num";

    private static final int REFUND_NUM_LENGTH = 7;

    @Override
    public Long saveLoadOrder(LoadOrderDTO dto) {
        log.info("saveLoadOrder-新增装卸服务订单,dto={}", dto);
        if (CollectionUtils.isEmpty(dto.getDetails())) {
            throw BizException.wrap("订单明细不能为空");
        }
        dto.setOrderType(LogisticsOrderTypeEnum.LOAD.getCode());
        // 生成订单编号
        dto.setOrderNum(generateOrderNum());
        LogisticsOrder order = new LogisticsOrder();
        BeanUtils.copyProperties(dto, order);
        order.setDetails(JSON.toJSONString(dto.getDetails()));
        save(order);
        log.info("saveLoadOrder-新增装卸服务订单成功,model={}", order);
        return order.getId();
    }

    @Override
    public void updateLoadOrder(LoadOrderDTO dto) {
        log.info("updateLoadOrder-修改装卸服务订单,dto={}", dto);
        LogisticsOrder one = lambdaQuery().eq(LogisticsOrder::getId, dto.getId()).one();
        if (Objects.isNull(one)) {
            throw BizException.wrap("订单不存在,id={}", dto.getId());
        }
        dto.setOrderType(LogisticsOrderTypeEnum.LOAD.getCode());
        LogisticsOrder order = new LogisticsOrder();
        BeanUtils.copyProperties(dto, order);
        if (CollectionUtils.isNotEmpty(dto.getDetails())) {
            order.setDetails(JSON.toJSONString(dto.getDetails()));
        }
        updateById(order);
        log.info("updateLoadOrder-修改装卸服务订单成功,model={}", order);
    }


    @Override
    public LogisticsOrderVo getLogisticsOrderById(Long id) {
        log.info("getLogisticsOrderById-通过Id查询订单详情,id={}", id);
        LogisticsOrder model = lambdaQuery().eq(LogisticsOrder::getId, id).one();
        LogisticsOrderVo vo = new LogisticsOrderVo();
        BeanUtils.copyProperties(model, vo);
        if (LogisticsOrderTypeEnum.LOAD.getCode().equals(model.getOrderType())) {
            // 装卸服务订单
            String detailsJson = model.getDetails();
            List<LoadDetailsVo> details = JSON.parseArray(detailsJson, LoadDetailsVo.class);
            vo.setDetails(details);
        } else {
            // todo 仓储服务订单
        }
        return vo;
    }

    @Override
    public Page<LogisticsOrderVo> queryLogisticsOrderPage(PageParams<LogisticsOrderPageQuery> pageParams) {
        log.info("queryLogisticsOrderPage - 查询物流列表, pageParams={}", pageParams);
        Page<LogisticsOrder> pageParam = pageParams.buildPage();
        QueryWrapper<LogisticsOrder> queryWrapper = createLogisticsOrderQueryWrapper(pageParams);
        Page<LogisticsOrder> page = page(pageParam, queryWrapper);
        Page<LogisticsOrderVo> voPage = new Page<>();
        BeanUtil.copyProperties(page, voPage);
        List<LogisticsOrder> list = page.getRecords();
        if (list == null || list.isEmpty()) {
            return voPage;
        }

        List<LogisticsOrderVo> voList = list.stream().map(model -> {
            LogisticsOrderVo vo = BeanUtil.toBean(model, LogisticsOrderVo.class);
            if (LogisticsOrderTypeEnum.LOAD.getCode().equals(model.getOrderType())) {
                // 装卸服务订单
                String detailsJson = model.getDetails();
                List<LoadDetailsVo> details = JSON.parseArray(detailsJson, LoadDetailsVo.class);
                vo.setDetails(details);
            } else {
                // todo 仓储服务订单
            }
            return vo;
        }).collect(Collectors.toList());
        voPage.setRecords(voList);
        return voPage;
    }

    /**
     * 拼接查询条件
     *
     * @param params
     * @return
     */
    private QueryWrapper<LogisticsOrder> createLogisticsOrderQueryWrapper(PageParams<LogisticsOrderPageQuery> params) {
        LogisticsOrderPageQuery model = params.getModel();
        QueryWrapper<LogisticsOrder> queryWrapper = new QueryWrapper<>();
        queryWrapper
                .lambda()
                .eq(StrUtil.isNotBlank(model.getOrderNum()), LogisticsOrder::getOrderNum, model.getOrderNum())
                .like(StrUtil.isNotBlank(model.getEnterpriseName()), LogisticsOrder::getEnterpriseName, model.getEnterpriseName())
                .eq(StrUtil.isNotBlank(model.getOrderType()), LogisticsOrder::getOrderType, model.getOrderType())
                .eq(StrUtil.isNotBlank(model.getPayStatus()), LogisticsOrder::getPayStatus, model.getPayStatus())
        ;
        if (StrUtil.isNotBlank(params.getOrder())) {
            if (StrUtil.isNotBlank(params.getOrder())) {
                queryWrapper.orderBy(false, "ASC".equals(params.getSort().toUpperCase()), params.getOrder());
            }
        }
        return queryWrapper;
    }

    /**
     * 生成订单编号
     *
     * @return
     */
    private String generateOrderNum() {
        // 生成订单号
        String prefix = LocalDateTimeUtil.format(LocalDate.now(), "yyyyMMddmmHHssSSS");
        String orderNum = CreatCode.creatCode(baseMapper, REFUND_NUM_FIELD, REFUND_NUM_LENGTH, prefix);
        return orderNum;
    }
}
